#ifndef DISPATCHER_HANDLER_H
#define DISPATCHER_HANDLER_H

#include "Scheduler.h"
#include "AnalogPort.h"
#include <SN74AHC595.h>
#include <module_general_reg.h>
#include "DataStorage.h"
#include "IOPort.h"

class DispatcherHandler : public Scheduler
{
public:
    enum class ActionState{Inactive,Ready,Running,WaitingDelay,OutputAction,Exit};
    typedef struct
    {
        ActionState state;
        uint16_t input_voltage[2];
        unsigned long last_millis[2];
    }logic_condition_t;

    // enum class AName{A0,A1,A2,A3};
    enum class ConditionActionName{CA0,CA1,CA2,CA3,CA4,CA5,CA6,CA7};
    
    typedef enum{
        Manual  = 0,
        Auto    = 1
    }WorkMode;
    DispatcherHandler(IOPort& ioport,ti::SN74AHC595& sn74ahc595,DataStorage& ds,PinName pin_int);
    ~DispatcherHandler();

    void begin();
    void schedule() override;
    void update() override;
    void dispatch(uint8_t* data,size_t size) override;
    void cleanup()override;
    void reset_work_mode(module_general_reg_t& general_reg);
    void clear_interrupt();
    data_storage_reg_read_t& get_reg_data(uint8_t reg_address);

protected:
    //int apply_median_filter(AnalogIn & an);

    bool apply_input_compare(uint8_t condition_id,uint8_t input_condition_id);
    bool apply_time_compare(uint8_t condition_id,uint8_t time_condition_id);

    bool apply_condition_compare(uint8_t id);

    void apply_output_action(uint8_t id);

    void control_action_output(output_action_details_t& action);


private:
    IOPort& _ioport;
    ti::SN74AHC595& _sn74ahc595;
    DataStorage& _ds;
    DigitalOut _interrupt_pin;

    
    data_storage_reg_read_t _reg_read;


    unsigned long _sample_interval_ms;

    WorkMode _workMode;

    ConditionActionName  _conditionActionName;

    logic_condition_t _logic_conditions[8];
};
#endif